<template>
  <div class="app-container">
    <!-- 宴席搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="选择宴席" prop="banquetId">
        <el-select
          v-model="queryParams.banquetId"
          filterable
          remote
          reserve-keyword
          placeholder="输入宴席主办人姓名搜索"
          :remote-method="searchBanquet"
          :loading="banquetLoading"
          @change="handleBanquetSelect"
        >
          <el-option
            v-for="item in banquetOptions"
            :key="item.id"
            :label="`${item.hostName}（桌数：${item.tableCount}）`"
            :value="item.id"
          >
            <span style="float: left ; color: #8492a6; font-size: 14px">主办人：{{ item.hostName }}</span>
            <span style="float: right; color: #8492a6; font-size: 14px">桌数：{{ item.tableCount }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 生成配料表按钮 -->
      <el-form-item>
        <el-button
          type="success"
          icon="el-icon-document"
          @click="generateAndShowMaterialList"
          :loading="generateLoading"
          :disabled="selectedDishIds.length === 0"
        >生成配料表
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 已选菜品展示 -->
    <el-table
      :data="selectedDishes"
      border
      style="margin-bottom: 20px"
      v-if="selectedDishes.length > 0"
    >
      <el-table-column label="菜品名称" prop="dishName">
        <template slot-scope="scope">
          {{ scope.row.dishName }}
          <el-tag v-if="scope.row.duplicate" type="warning" size="mini" style="margin-left: 5px">
            已添加
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template slot-scope="scope">
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeDish(scope.$index)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 菜品选择区域 -->
    <div v-if="queryParams.banquetId" class="dish-selection-area">
      <!-- 菜品搜索 -->
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="输入菜品名称搜索"
          clearable
          prefix-icon="el-icon-search"
          style="width: 300px;"
        />
      </div>

      <!-- 已选菜品计数 -->
      <div class="selected-count">
        已选择 {{ selectedDishIds.length }} 个菜品
      </div>

      <!-- 菜品列表 -->
      <div class="dish-grid">
        <el-checkbox-group v-model="selectedDishIds" @change="handleSelectionChange">
          <div class="dish-list">
            <div v-for="dish in filteredDishes" :key="dish.id" class="dish-item">
              <el-checkbox :label="dish.id">
                {{ dish.dishName }}
              </el-checkbox>
            </div>
          </div>
        </el-checkbox-group>
      </div>
    </div>

    <!-- 提示选择宴席 -->
    <el-empty v-else description="请先选择宴席"></el-empty>
  </div>
</template>

<script>
import {listBanquet, generateMaterialReport} from '@/api/catering/banquet'
import {listAllDishes} from '@/api/catering/dish'

export default {
  name: 'BanquetOrder',
  data() {
    return {
      queryParams: {
        banquetId: null,
        tables: 0
      },
      banquetOptions: [],
      banquetLoading: false,
      selectedDishes: [],
      showDishDialog: false,
      generateLoading: false,
      materialList: [],
      isPrinting: false,
      dishes: [], // 所有菜品列表
      selectedDishIds: [], // 已选菜品ID
      searchKeyword: '', // 搜索关键词
      dishLoading: false
    }
  },
  methods: {
    // 新增方法：生成并在新标签页显示配料表
    async generateAndShowMaterialList() {
      try {
        // 调用原方法获取数据
        const materialList = await this.generateMaterialList()
        if (!materialList || materialList.length === 0) {
          this.$message.warning('没有获取到配料数据')
          return
        }

        // 获取当前宴席信息
        const currentBanquet = this.banquetOptions.find(item => item.id === this.queryParams.banquetId) || {}

        // 打开新标签页并显示配料表
        this.openMaterialListInNewTab(materialList, currentBanquet)
      } catch (error) {
        console.error('生成配料表失败', error)
        this.$message.error('生成配料表失败，请重试')
      }
    },

    // 在新标签页打开配料表
    openMaterialListInNewTab(materialList, banquetInfo) {
      const newWindow = window.open('', '_blank');
      if (!newWindow) {
        this.$message.error('无法打开新窗口，请检查浏览器的弹窗设置');
        return;
      }

      // 1. 根据数据动态获取所有分类并分组
      const groupedMaterials = materialList.reduce((acc, item) => {
        const category = item.category || '其他';
        if (!acc[category]) {
          acc[category] = [];
        }
        // 确保每个item都有remark字段，即使是空字符串
        acc[category].push({...item, remark: item.remark || ''});
        return acc;
      }, {});

      // 2. 按分类下的菜品数量降序排列分类
      const sortedCategories = Object.keys(groupedMaterials).sort(
        (a, b) => groupedMaterials[b].length - groupedMaterials[a].length
      );

      // 3. 将排序后的分类分成左右两列
      const midPoint = Math.ceil(sortedCategories.length / 2);
      const leftCategories = ['水产海鲜', '肉类', '仓库'];
      let rightCategories = sortedCategories.filter(category => !leftCategories.includes(category));

      const customOrder = ['蔬菜', '干货', '家禽类'];
      rightCategories = rightCategories.sort((a, b) => {
        const indexA = customOrder.indexOf(a);
        const indexB = customOrder.indexOf(b);
        if (indexA === -1 && indexB === -1) return 0;
        if (indexA === -1) return 1;
        if (indexB === -1) return -1;
        return indexA - indexB;
      });

      // 4. 生成列内容的函数 (包含备注列)
      const generateColumnContent = (categories) => {
        return categories.map(category => {
          const materials = groupedMaterials[category] || [];
          if (materials.length === 0) {
            return ''; // 如果没有配料，则不生成内容
          }
          return `
      <div class="category-section">
        <div class="category-title">${category} (${materials.length}项)</div>
        <table class="material-table">
          ${materials.map(item => `
            <tr>
              <td>${item.materialName}(${item.unit})</td>
              <td>
                <input type="number"
                       value="${item.perTable}"
                       min="0"
                       step="0.1"
                       class="amount-input"
                       data-id="${item.id || ''}"
                       oninput="validateNumberInput(this)">
              </td>
              <td>
                <input type="text"
                       value="${item.remark}"
                       class="remark-input"
                       data-id="${item.id || ''}">
              </td>
            </tr>
          `).join('')}
        </table>
      </div>
    `;
        })
          .filter(content => content !== '') // 过滤掉空内容
          .join('');
      };

      // 5. 生成左右两列的HTML
      const leftColumnHtml = generateColumnContent(leftCategories);
      const rightColumnHtml = generateColumnContent(rightCategories);

      // 6. 写入新窗口的HTML内容
      newWindow.document.write(`
        <html>
          <head>
            <title>宴席配料汇总表</title>
            <style>
              /* --- 样式与上一个版本基本相同，只保留必要的 --- */
              @page { size: A4; margin: 1cm; }
              body { font-family: Arial, sans-serif; padding: 10px; max-width: 21cm; margin: 0 auto; font-size: 25px; }
              .header { text-align: center; margin-bottom: 10px; }
              .banquet-info-container { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; font-size: 25px; }
              .content-container { display: flex; justify-content: space-between; gap: 15px; }
              .column { flex: 1; }
              .category-section { margin-bottom: 10px; }
              .category-title { font-weight: bold; padding: 3px 0; border-bottom: 1px solid #000; margin-bottom: 4px; }
              .material-table { width: 100%; border-collapse: collapse; font-size: 15px; margin-bottom: 5px; }
              .material-table td { padding: 3px 4px; border: none; vertical-align: middle; font-size: 20px; }
              .material-table td:nth-child(1) { width: 35%; } /* 配料名称 */
              .material-table td:nth-child(2) { width: 35%; text-align: center; } /* 数量 */
              .material-table td:nth-child(3) { width: 30%; } /* 备注 */
              .amount-input, .remark-input { border: 1px solid #dcdfe6; border-radius: 2px; padding: 2px 3px; font-size: 20px; box-sizing: border-box; }
              .amount-input { width: 80px; text-align: center; }
              .remark-input { width: 100%; }
              .print-btn { background-color: #409EFF; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; } /* 调整按钮大小 */
              @media print {
                body { font-size: 25px; }
                .print-btn { display: none !important; }
                .amount-input, .remark-input { border: none; background: transparent; padding: 0; }
                .material-table td { padding: 2px 3px; }
              }
            </style>
            <script>
              // 只保留必要的JS：打印和简单的输入验证
              function validateNumberInput(input) {
                const value = parseFloat(input.value);
                if (isNaN(value) || value < 0) {
                  input.value = 0; // 非法输入或负数置为0
                }
              }

              function printTable() {
                window.print();
              }
            <\/script>
          </head>
          <body>
            <div class="header">
              <h2 style="margin: 0;">宴席配料汇总表</h2>
            </div>

            <div class="banquet-info-container">
              <div class="banquet-info">
                <span><strong>主办人：</strong>${banquetInfo.hostName || '未指定'}</span>
                <span style="margin-left: 20px;"><strong>桌数：</strong>${banquetInfo.tableCount || 0}</span>
              </div>
              <button class="print-btn" onclick="printTable()" style="flex-shrink: 0;">打印表格</button>
            </div>

            <div class="content-container">
              <!-- 左列 -->
              <div class="column">
                ${leftColumnHtml}
              </div>
              <!-- 右列 -->
              <div class="column">
                ${rightColumnHtml}
              </div>
            </div>
          </body>
        </html>
      `);
      newWindow.document.close();
    },
    // 搜索宴席
    searchBanquet(query) {
      if (query) {
        this.banquetLoading = true
        listBanquet({hostName: query}).then(res => {
          this.banquetOptions = res.rows
        }).finally(() => {
          this.banquetLoading = false
        })
      }
    },

    // 选择宴席
    async handleBanquetSelect(val) {
      const selected = this.banquetOptions.find(item => item.id === val)
      this.queryParams.tables = selected?.tables || 0
      this.selectedDishIds = [] // 清空已选菜品
      await this.loadAllDishes() // 加载菜品列表
    },
    // 加载所有菜品
    async loadAllDishes() {
      try {
        this.dishLoading = true
        const res = await listAllDishes()
        this.dishes = res.data || []
      } catch (error) {
        console.error('加载菜品失败:', error)
        this.$message.error('加载菜品列表失败')
      } finally {
        this.dishLoading = false
      }
    },

    // 处理菜品选择变化
    handleSelectionChange(value) {
      this.selectedDishIds = value
    },
    // 删除菜品
    removeDish(index) {
      this.selectedDishes.splice(index, 1)
    },

    // 生成配料表
    async generateMaterialList() {
      if (!this.queryParams.banquetId) {
        this.$message.warning('请先选择宴席')
        return
      }
      try {
        this.generateLoading = true
        const params = {
          banquetId: this.queryParams.banquetId,
          dishIds: this.selectedDishIds
        }
        const res = await generateMaterialReport(params)

        this.materialList = res.data.map(item => ({
          ...item,
          perTable: Number(item.perTable || 0).toFixed(2) // 确保初始值格式
        }));
        return this.materialList;
      } finally {
        this.generateLoading = false
      }
    },
  },
  computed: {
    // 过滤后的菜品列表
    filteredDishes() {
      if (!this.searchKeyword) {
        return this.dishes
      }
      const keyword = this.searchKeyword.toLowerCase()
      return this.dishes.filter(dish =>
        dish.dishName.toLowerCase().includes(keyword)
      )
    }
  },
  mounted() {
    window.addEventListener("beforeprint", () => {
      this.isPrinting = true;
    });
    window.addEventListener("afterprint", () => {
      this.isPrinting = false;
    });
  }

}
</script>

<style scoped>
.dish-selection-area {
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-box {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-count {
  margin-bottom: 15px;
  color: #606266;
  font-size: 14px;
}

.dish-grid {
  max-height: 60vh;
  overflow-y: auto;
}

.dish-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  padding: 10px;
}

.dish-item {
  padding: 8px;
  border-radius: 4px;
  background-color: #f5f7fa;
  transition: background-color 0.3s;
}

.dish-item:hover {
  background-color: #ebeef5;
}

/* 自定义滚动条样式 */
.dish-grid::-webkit-scrollbar {
  width: 6px;
}

.dish-grid::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.dish-grid::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 适配移动端 */
@media screen and (max-width: 768px) {
  .dish-list {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>
